package com.cet6.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cet6.entity.StudyRecord;
import com.cet6.mapper.StudyRecordMapper;
import com.cet6.service.StudyRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class StudyRecordServiceImpl extends ServiceImpl<StudyRecordMapper, StudyRecord> implements StudyRecordService {
    
    @Autowired
    private StudyRecordMapper studyRecordMapper;
    
    @Override
    @Transactional
    public boolean saveOrUpdateStudyRecord(StudyRecord studyRecord) {
        // 查询是否已存在记录
        StudyRecord existingRecord = studyRecordMapper.selectByUserIdAndWordId(
            studyRecord.getUserId(), studyRecord.getWordId());
        
        if (existingRecord != null) {
            // 更新现有记录
            existingRecord.setStatus(studyRecord.getStatus());
            existingRecord.setStudyCount(existingRecord.getStudyCount() + 1);
            existingRecord.setLastStudyTime(LocalDateTime.now());
            existingRecord.setMasteryLevel(studyRecord.getMasteryLevel());
            existingRecord.setUpdateTime(LocalDateTime.now());
            return this.updateById(existingRecord);
        } else {
            // 插入新记录
            studyRecord.setStudyCount(1);
            studyRecord.setLastStudyTime(LocalDateTime.now());
            studyRecord.setCreateTime(LocalDateTime.now());
            studyRecord.setUpdateTime(LocalDateTime.now());
            studyRecord.setDeleted(0);
            return this.save(studyRecord);
        }
    }
    
    @Override
    public StudyRecord getStudyRecordByUserIdAndWordId(Long userId, Long wordId) {
        return studyRecordMapper.selectByUserIdAndWordId(userId, wordId);
    }
}
